package com.khyr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.khyr.Vo.*;
import com.khyr.dao.MedicinesDao;
import com.khyr.dao.PurchaseDao;
import com.khyr.dao.PurchaseInVentoryLog;
import com.khyr.dao.PurchaseItemDao;
import com.khyr.entity.*;
import com.khyr.feign.UserFeign;
import com.khyr.service.PurchaseService;
import com.khyr.utils.SnowflakeIdGenerator;
import com.khyr.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @className: PurchaseServiceImpl
 * @author: Zyl
 * @date: 2025/3/13 14:55
 * @Version: 1.0
 * @description:
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {
    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private PurchaseItemDao purchaseItemDao;
    @Autowired
    private PurchaseInVentoryLog purchaseInVentoryLog;
    @Autowired
    private MedicinesDao medicinesDao;
    @Override
    // 查询采购单【采购管理界面】
    public R<Page<StockPurchase>> findPurchase(PurchaseVo data) {
        QueryWrapper<StockPurchase> queryWrapper = new QueryWrapper<>();
        if(data.getProviderId() != null){
            queryWrapper.eq("provider_id",data.getProviderId());
        }
        if(data.getApplyUserName() != null){
            queryWrapper.like("apply_user_name",data.getApplyUserName());
        }
        if(data.getStatus() != null){
            queryWrapper.eq("status",data.getStatus());
        }
        //添加创建时间createTime按降序排列的条件
        queryWrapper.orderByDesc("create_time");
        Page<StockPurchase> page = new Page<>(data.getPageNum(), data.getPageSize());
        Page<StockPurchase> stockPurchasePage = purchaseDao.selectPage(page, queryWrapper);
        return new R<>(200,"查询成功",stockPurchasePage);
    }

    @Override
    // 生成单据号-新增采购界面
    public R generatePurchaseId() {
        //制单号id利用雪花算法
        String  purchaseId = "AAA"+SnowflakeIdGenerator.nextId();

        return new R<>(200,"生成成功",purchaseId);
    }

    @Override
    // 添加采购单和详情【新增采购页面】
    public R addPurchase(PurchaserVo2 data) {
        String token = request.getHeader("token");
        String name=userFeign.getUserInfo(token).getData().getUserName();
//        data.setApplyUserName(name);
//        data.setPurchaseId(generatePurchaseId().getData().toString());
        PurchaseDTO purchaseDto = data.getPurchaseDto();
        data.setPurchaseId(purchaseDto.getPurchaseId());
        data.setApplyUserName(name);
        data.setProviderId(purchaseDto.getProviderId());
        data.setPurchaseTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());
        List<PurchaseItemDTO> purchaseItemDtos = data.getPurchaseItemDtos();
        //遍历
        for (PurchaseItemDTO purchaseItemDto : purchaseItemDtos) {
            purchaseItemDto.setPurchaseId(purchaseDto.getPurchaseId());
            String  purchaseId = "AAA"+SnowflakeIdGenerator.nextId();
            purchaseItemDto.setItemId(purchaseId);
            purchaseItemDao.insert2(purchaseItemDto);
        }
        int i = purchaseDao.insert1(data);
        if(i > 0){
            return new R<>(200,"添加成功",null);
        }else{
            return new R<>(500,"添加失败",null);
        }
    }

    @Override
    //查询状态为待审核的采购单【采购管理界面】status=2
    public R<Page<StockPurchase>> findPurchase2(PurchaseVo data) {
        QueryWrapper<StockPurchase> queryWrapper = new QueryWrapper<>();
        if(data.getProviderId() != null){
            queryWrapper.eq("provider_id",data.getProviderId());
        }
        if(data.getApplyUserName() != null){
            queryWrapper.like("apply_user_name",data.getApplyUserName());
        }
        //查status 为2 的
        queryWrapper.eq("status",2);
        Page<StockPurchase> page = new Page<>(data.getPageNum(), data.getPageSize());
        Page<StockPurchase> stockPurchasePage = purchaseDao.selectPage(page, queryWrapper);
        return new R<>(200,"查询成功",stockPurchasePage);
    }

    @Override
    // 根据采购单ID查询采购单信息和详情
    public R<PurcharserVo3> queryPurchaseAndItemByPurchaseId(String purchaseId) {
        StockPurchase purchase = purchaseDao.selectOne(new QueryWrapper<StockPurchase>().eq("purchase_id", purchaseId));
      List<StockPurchaseItem> list = purchaseItemDao.selectList(new QueryWrapper<StockPurchaseItem>().eq("purchase_id", purchaseId));
        PurcharserVo3 purcharserVo3 = new PurcharserVo3(purchase, list);
        return new R<>(200,"查询成功",purcharserVo3);
    }

    @Override
    // 提交审核【主页面】
    public R doInvalid(String purchaseId) {
        Date date = new Date();
        int i = purchaseDao.update(null, new UpdateWrapper<StockPurchase>()
                .eq("purchase_id", purchaseId)
                .set("status", 2)
                .set("create_time",date));
        if(i > 0){
            return new R<>(200,"提交成功",null);
        }else{
            return new R<>(500,"提交失败",null);
        }

    }

    @Override
    public R addPurchase2(PurchaserVo2 data) {
        String token = request.getHeader("token");
        String name=userFeign.getUserInfo(token).getData().getUserName();

        PurchaseDTO purchaseDto = data.getPurchaseDto();
        data.setPurchaseId(purchaseDto.getPurchaseId());
        data.setApplyUserName(name);
        data.setProviderId(purchaseDto.getProviderId());
        data.setPurchaseTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());
        List<PurchaseItemDTO> purchaseItemDtos = data.getPurchaseItemDtos();
        //遍历
        for (PurchaseItemDTO purchaseItemDto : purchaseItemDtos) {
            purchaseItemDto.setPurchaseId(purchaseDto.getPurchaseId());
            String  purchaseId = "AAA"+SnowflakeIdGenerator.nextId();
            purchaseItemDto.setItemId(purchaseId);
            purchaseItemDao.insert2(purchaseItemDto);
        }
        int i = purchaseDao.insert2(data);
        if(i > 0){
            return new R<>(200,"添加成功",null);
        }else{
            return new R<>(500,"添加失败",null);
        }
    }

    @Override
    //作废
    public R del(String purchaseId) {
        // 只用状态为1，4 的作废,使状态变成为5
        int i = purchaseDao.update(null, new UpdateWrapper<StockPurchase>()
                .eq("purchase_id", purchaseId)
                .in("status", 1, 4) // 只更新状态为1或4的记录
                .set("status", 5)); // 将状态更新为5
        if (i > 0) {
            return new R<>(200, "作废成功",null);
        }
        return null;
    }
    @Override
    //提交入库,先判断状态是否为3，为3进行业务操作，不为3显示请审核通过后入库
    public R doInventory(String purchaseId) {
        String token = request.getHeader("token");
        String name=userFeign.getUserInfo(token).getData().getUserName();
        // 先查询采购单状态
       List<StockPurchaseItem>  purchase = purchaseItemDao.selectList(new QueryWrapper<StockPurchaseItem>().eq("purchase_id", purchaseId));

        if (purchase == null) {
            return new R<>(500, "采购单不存在", null);
        }
        StockPurchase purchaseId1 = purchaseDao.selectById(purchaseId);
        String status = purchaseId1.getStatus();
        // 判断状态是否为3（审核通过）
        if (!status.equals("3")) {
            return new R<>(400, "只有审核通过状态才能入库", null);
        }
        // 将数据添加到 stock_inventory_log 表
        for (StockPurchaseItem item : purchase) {
            // 将数量添加到 stock_medicines 表
            StockMedicines stockMedicines = medicinesDao.selectById(item.getMedicinesId());
            if(stockMedicines != null){
                StockMedicines m = new StockMedicines();
                m.setMedicinesId(stockMedicines.getMedicinesId());
                m.setMedicinesStockNum(item.getPurchaseNumber());
                medicinesDao.update(m);
            }
            // 将数据添加到 stock_inventory_log 表
            StockInventoryLog log = new StockInventoryLog();
            log.setPurchaseId(purchaseId);
            String  inloid = "AAA"+SnowflakeIdGenerator.nextId();
            log.setInventoryLogId(inloid);
            log.setMedicinesId(item.getMedicinesId());
            //入库的数量
            log.setInventoryLogNum(item.getPurchaseNumber());
            log.setTradePrice(item.getTradePrice());
            log.setTradeTotalAmount(item.getTradeTotalAmount());
            log.setBatchNumber(item.getBatchNumber());
            log.setMedicinesName(item.getMedicinesName());
            log.setMedicinesType(item.getMedicinesType());
            log.setPrescriptionType(item.getPrescriptionType());
            log.setProducterId(item.getProducterId());
            log.setConversion(item.getConversion());
            log.setUnit(item.getUnit());
            log.setProviderId(purchaseId1.getProviderId());
            log.setCreateTime(new Date());
            log.setCreateBy(name);
            //加入处方的价格
            log.setPrescriptionPrice(stockMedicines.getPrescriptionPrice());
            //将入库数量int 转为 BigDecimal
            BigDecimal purchaseNumber = new BigDecimal(item.getPurchaseNumber());
            //使用BigDecimal的乘法方法
            BigDecimal multiply = purchaseNumber.multiply(stockMedicines.getPrescriptionPrice());
            //加入处方金额
            log.setPrescriptionTotalAmount(multiply);
            purchaseInVentoryLog.insert(log);
        }
        purchaseDao.in(name,purchaseId,null);// 更新库存
        // 更新采购单状态为已入库（假设状态 6 表示已入库）
        purchaseDao.update(null, new UpdateWrapper<StockPurchase>()
                .eq("purchase_id", purchaseId)
                .set("status", 6));
        return new R<>(200, "入库成功", null);

    }


    @Override
    // 审核不通过【根据采购单号】
    public R auditNoPass(String purchaseId, String auditMsg) {
        // 更新采购单状态为4，并添加审核信息auditMsg
        int i = purchaseDao.update(null, new UpdateWrapper<StockPurchase>()
                .eq("purchase_id", purchaseId)
                .set("status", 4)
                .set("audit_msg", auditMsg));
        if (i > 0) {
            return new R<>(200, "审核不通过成功", null);
        } else {
            return new R<>(500, "审核不通过失败", null);
        }

    }

    @Override
    //点击订单后可以再次修改暂存
    public R up(PurchaserVo2 data) {
        String token = request.getHeader("token");
        String name=userFeign.getUserInfo(token).getData().getUserName();
        data.setApplyUserName(name);

        PurchaseDTO purchaseDto = data.getPurchaseDto();
        data.setPurchaseId(purchaseDto.getPurchaseId());
        data.setProviderId(purchaseDto.getProviderId());
        data.setPurchaseTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());

        List<PurchaseItemDTO> purchaseItemDtos = data.getPurchaseItemDtos();
        //遍历删除
        for (PurchaseItemDTO purchaseItemDto : purchaseItemDtos) {
            purchaseItemDao.delete(new QueryWrapper<StockPurchaseItem>().eq("item_id", purchaseItemDto.getItemId()));
        }
        //遍历添加
        for (PurchaseItemDTO purchaseItemDto : purchaseItemDtos) {
            purchaseItemDto.setPurchaseId(purchaseDto.getPurchaseId());
            String  purchaseId = "AAA"+SnowflakeIdGenerator.nextId();
            purchaseItemDto.setItemId(purchaseId);
            purchaseItemDao.insert2(purchaseItemDto);
        }
        int i = purchaseDao.up(data);
        if(i > 0){
            return new R<>(200,"添加成功",null);
        }else{
            return new R<>(500,"添加失败",null);
        }
    }

    @Override
    // 点击订单后可以再次提交审核
    public R up2(PurchaserVo2 data) {
        String token = request.getHeader("token");
        String name=userFeign.getUserInfo(token).getData().getUserName();
        data.setApplyUserName(name);

        PurchaseDTO purchaseDto = data.getPurchaseDto();
        data.setPurchaseId(purchaseDto.getPurchaseId());
        data.setProviderId(purchaseDto.getProviderId());
        data.setPurchaseTradeTotalAmount(purchaseDto.getPurchaseTradeTotalAmount());

        List<PurchaseItemDTO> purchaseItemDtos = data.getPurchaseItemDtos();
        //遍历删除
        for (PurchaseItemDTO purchaseItemDto : purchaseItemDtos) {
            purchaseItemDao.delete(new QueryWrapper<StockPurchaseItem>().eq("item_id", purchaseItemDto.getItemId()));
        }
        //遍历添加
        for (PurchaseItemDTO purchaseItemDto : purchaseItemDtos) {
            purchaseItemDto.setPurchaseId(purchaseDto.getPurchaseId());
            String  purchaseId = "AAA"+SnowflakeIdGenerator.nextId();
            purchaseItemDto.setItemId(purchaseId);
            purchaseItemDao.insert2(purchaseItemDto);
        }
        int i = purchaseDao.up2(data);
        if(i > 0){
            return new R<>(200,"添加成功",null);
        }else{
            return new R<>(500,"添加失败",null);
        }
    }

    @Override
    public R auditPass(String purchaseId) {
        // 更新采购单状态为3，并设置审核信息audit_msg为"已通过"
        int i = purchaseDao.update(null, new UpdateWrapper<StockPurchase>()
                .eq("purchase_id", purchaseId)
                .set("status", 3)
                .set("audit_msg", "已通过"));
        if (i > 0) {
            return new R<>(200, "审核通过成功", null);
        } else {
            return new R<>(500, "审核通过失败", null);
        }
    }

}
